<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Catalogue extends TMT_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper('html');
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->library('pagination');

        //$this->load->model('catalogue_model');
    }

    function index() 
    {
        $this->clear_filters();
    }

    public function show() {
		$this->show_sidebar 	= FALSE;
		$this->headline 		= 'Schulungskatalog';
		
		$teamroles = $this->employee->teamrole();
		$active_teamrole 		= $teamroles[$this->active_team];
		
		
		
		switch($active_teamrole->roletype()->name)
		{
			case 'Admin':
			case 'Teamleitung': $this->view_data['role'] 	= 'teamleader'; break;
			case 'Management': 	$this->view_data['role'] 	= 'management'; break;
			default: redirect(''); break;
		}
		
		
		$this->view_data['form_data'] = '';
		
		$filters = NULL;
		/*
		 Choose which Data to pick:
		If Post-Variables are empty, take data from the session Variable
		*/
			
		if($this->input->post('filter_submit'))
		{
			$filters['fb_filter'] = $this->input->post('Fachbereich_Filter');
			$filters['ft_filter'] = $this->input->post('Fachthema_Filter');
			$filters['be_filter'] = $this->input->post('Bedarf_Filter');
		}
		else
		{
			$filters['ft_filter'] = $this->session->userdata('ft_filter');
			$filters['fb_filter'] = $this->session->userdata('fb_filter');
			$filters['be_filter'] = $this->session->userdata('be_filter');
		}
		
		// Set new data or replace/renew the old one
		$this->session->set_userdata($filters);
		/*
		if($this->input->get('action') == 'switch' AND $this->input->get('stopeid') AND $active_teamrole->roletype()->name == 'Teamleitung')
		{
			$this->view_data['target'] = 'catalogue/switch_stope';
			$this->view_data['stope']  = '?stopeid=' . $this->input->get('stopeid');
			$this->view_data['btn']    = array('text' => 'Tauschen', 'css' => 'btn btn-primary btn-small');
				}
		else if($active_teamrole->roletype()->name == 'Teamleitung')
		{
		
			$this->view_data['target'] = 'booking/select_training';
			$this->view_data['stope']  = NULL;
			$this->view_data['btn']    = array('text' => 'Buchen', 'css' => 'btn btn-small');
			$form_data['form_target'] = 'catalogue/show';
		}
		else if($active_teamrole->roletype()->name == 'Management')
		{
			$this->view_data['target'] = 'measure/create';
			$this->view_data['stope']  = NULL;
			$this->view_data['btn']    = array('text' => 'Maßnahme erstelllen', 'css' => 'btn btn-small');
			$form_data['form_target'] = 'catalogue/show';
		}
		*/
		$this->view_data['course_form']['hidden'] = array();
		$form_data['form_target'] = 'catalogue/show';
        
		
		switch($this->input->get('action'))
		{
			case 'switch':
				$this->view_data['course_form']['target'] 					= 'booking/select_bedarf';
				$this->view_data['course_form']['hidden']['stope_id'] 		= $this->input->get('stopeid');
				$this->view_data['course_form']['hidden']['teammember_id'] 	= 
                                        Model\Stopedemand::find($this->input->get('stopeid'))->employee()->id;
				$this->view_data['course_form']['button'] 					= array('type' 	=> 'submit',
																					'name' 	=> 'submit', 
																					'class' =>'btn btn-primary',
																					'value' => 'Tauschen');
				$form_data['form_target'] = 'catalogue/show'. '?action=switch&stopeid='.$this->input->get('stopeid');
				
				break;
			default:
				switch($this->view_data['role'])
				{
					case 'teamleader':
						$this->view_data['course_form']['target'] = 'booking/select_training';
						$this->view_data['course_form']['button'] = array('type' 	=> 'submit',
																		  'name' 	=> 'submit', 
																		  'class' 	=>'btn btn-small',
																		  'value' 	=> 'Buchen');
						break;
					case 'management':
						$this->view_data['course_form']['target'] = 'training/create';
						$this->view_data['course_form']['button'] = array('type' 	=> 'submit',
																		  'name' 	=> 'submit',
																		  'class' 	=>'btn btn-small',
																		  'value' 	=> 'Maßnahme erstellen');
						break;
						
				}
				
				break;
		}
		
		
		$config['per_page']   = 50;
		//fetch offset
		$page 	= ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$count 	= 0;
		$data 	= Model\Catalogue::get_filtered($filters['ft_filter'],
												$filters['fb_filter'],
												$filters['be_filter'],
												$count);
		
		$target 					= min($count, $config['per_page']);
		$this->view_data['results'] = array();
		for($i = $page; $i < $page + $target; ++$i)
		{
			$this->view_data['results'][] = $data[$i];
		}
		$config['total_rows'] = $count;
		$config['per_page']   = 50;
		$config["base_url"]   = base_url() . "index.php/catalogue/show";
		$this->pagination->initialize($config);
		
		// Get URI Segment to route with the pagination
		$this->view_data['links']   = $this->pagination->create_links();
		
		// Prepare formular attributes
		if (!empty($filters['fb_filter']))
			$form_data['selected'] = $filters['fb_filter'];
		else
			$form_data['selected'] = '-- Kein Filter --';
		
		$form_data['faculties'][''] = '';
		foreach(Model\Faculty::all() as $faculty)
		{
			if('' != $faculty->title)
				$form_data['faculties'][$faculty->id] = $faculty->title;
		}
		
		$form_data['facht_filter'] = array('name' 		 => 'Fachthema_Filter',
										   'value' 		 => $filters['ft_filter'],
										   'placeholder' => 'Suche Schulung',
										   'class' 		 => 'span7'
											);
		
		$form_data['bedarf_filter'] = array('name'	=> 'Bedarf_Filter',
											'value' => $filters['be_filter'],
											'class' => 'span3'
											);
		
		$this->view_data['form_data'] = $form_data;
		$this->view_data['add'] = 'action=switch&stopeid='.$this->input->get('stopeid');
		
    }
	
    function clear_filters() 
	{
        $action = $this->input->get('action');
        $stopeid = $this->input->get('stopeid');
        
        $filters['ft_filter'] = NULL;
        $filters['fb_filter'] = NULL;
        $filters['be_filter'] = NULL;

        $this->session->set_userdata($filters);

        $link = 'catalogue/show';
        if($action) $link = $link . '?action='.$action;
        if($stopeid) $link = $link . '&stopeid='.$stopeid;
        
        redirect($link);
    }

    function details($id = NULL) 
    {
        $mode = $this->input->get('mode');
        
        $this->view_data['is_management'] = $this->employee->is_management();
	
        if (!isset($id))
            redirect('catalogue');

        if($mode == 'edit' && $this->employee->is_management())
        {
            $this->view_data['edit'] = TRUE;
			$faculties  = Model\Faculty::all();
            $this->view_data['faculties'] = array();
			
			foreach($faculties as $faculty)
			{
				if('' != $faculty->title)
					$this->view_data['faculties'][$faculty->id] = $faculty->title;
			}
			
        } else {
        	if($this->employee->is_management()) {
            	$this->view_data['display_toolbar'] = TRUE;
            }
        }
        $this->headline = 'Schulungsdetails';

        $this->view_data['row'] = Model\Course::find($id);
        
        if (empty($this->view_data['row']))
            redirect('catalogue');

    }
	
	public function edit()
	{
		if(!$this->employee->is_management()) {
			redirect('catalogue\details\\'.set_value('course_id'));
		}
		$this->load->library('form_validation');
		$_POST['price'] = str_replace('.','',$_POST['price']);
		$_POST['price']	= str_replace(',','.',$_POST['price']);
		
		$this->form_validation->set_rules('course_id','','required|is_natural');
		$this->form_validation->set_rules('course','','required|xss_clean');
		$this->form_validation->set_rules('faculty_id','','required|is_natural');
		$this->form_validation->set_rules('description','','xss_clean');
		$this->form_validation->set_rules('price','','greater_than[0]');
		$this->form_validation->set_rules('tt_code','','alpha_numeric|xss_clean');
		$this->form_validation->set_rules('tt_link','','prep_url');
		
		if($this->form_validation->run())
		{
			
			$course = Model\Course::find(set_value('course_id'));
			
			$course->title 			= set_value('course');
			
			$course->description 	= set_value('description');
			
			$cost = $course->cost();
			if($cost)
				$cost->amount = set_value('price');
			else
			{
				$costtype_id = Model\Cost::find_by_name('Schulungskosten')->id;
				
				if($costtype_id == NULL)
					$costtype_id = Model\Cost::make(array('name' => 'Schulungskosten'))->id;
				
				$cost = Model\Cost::make(array('amount' => set_value('price'), 'costtype_id' => $costtype_id));
			}
			$course->cost_id = $cost->id;
			$course->code = set_value('tt_code');
			$course->link = set_value('tt_link');
			$cost->save();
			$course->save();
			
			$faculty_course = Model\Faculty\Course::where('course_id',$course->id);
			$faculty_course->delete();
			$faculty_course = Model\Faculty\Course::make(array('course_id' => $course->id,'faculty_id' => set_value('faculty_id')));
			$faculty_course->save();
		}
		else
		{
			echo 'This didn\'t work\n'.validation_errors();
		}
		redirect('catalogue\details\\'.set_value('course_id'));
	}
    
    function switch_stope($fachthemenID = FALSE)
    {
		$this->headline = 'Schulung tauschen';
		
        $stopeid      = $this->input->get('stopeid');
        
        if($fachthemenID AND $stopeid)
        {    
            //$this->load->model('team/stope_model');
            //$stope_row = $this->stope_model->get_specific_stope($stopeid);
            $stopedemand = Model\Stopedemand::find($stopeid);
            
            $this->view_data['course'] = Model\Course::find($fachthemenID);
            
            $this->view_data['stope_fachthema'] = $stopedemand->course()->id;
            $this->view_data['employee']     = $stopedemand->employee()->contactdata()->surname . ', ' . $stopedemand->employee()->contactdata()->forename;
            $employee_id = $stope_row->MitarbeiterID;
            $this->view_data['mitarbeiterID']   = $stopedemand->employee()->id;
            
			$this->view_data['hidden'] = array('stopeid' => $stopeid, 'ma_id' => $ma_id, 'ft_id' => $fachthemenID);
        }
		else
		{
			redirect('catalogue');
		}
    }

    
    function compare()
    {
    	$this->load->helper('file');
    	$this->load->library('table');
    	
    	$file_old = read_file("C:\Users\mdennsta\Documents\Praxisprojekt 2\Database\DUMMY_TMT_Katalogimport_Vorlage.xml");//@readfile("C:\Users\mdennsta\Documents\Praxisprojekt 2\Database\DUMMY_TMT_Katalogimport_Vorlage.xml");
    	
    	$file_new = read_file("C:\Users\mdennsta\Documents\Praxisprojekt 2\Database\Schulungskatalog 2013 (V1.0).xml");
    	
    	
    	
    	$dom_old = new DOMDocument("1.0");
    	$dom_new = new DOMDocument("1.0");
    	
    	$dom_old->loadXML($file_old);
    	$dom_new->loadXML($file_new);
    	
    	$rows = $dom_old->getElementsByTagName('Row');
    	
    	$old_courses = array();
    	$new_courses = array();
    	$target_courses = array();
    	
    	$first_row = TRUE;
    	
    	foreach($rows as $row)
    	{
    		$cells = $row->getElementsByTagName('Cell');
    	
    		if($cells->length == '0')
    			continue;
    	
    		$data = array();
    	
    		foreach($cells as $cell)
    		{
    			if(!$first_row)
    			{
    				$data[] = $cell->nodeValue;
    			}
    			else
    			{
    				$first_row = FALSE;
    				break;
    			}
    		}
    		if(!isset($data[0]) || 
    			!isset($data[1]) || 
    				!isset($data[2]) || 
    				!isset($data[3]) || 
    				!isset($data[4]))
    		{
    			continue;
    		}
    		
    		$old_courses[trim($data[0])] = array('title' => trim($data[0]),
    				'cluster' => trim($data[1]),
    				'code' => trim($data[2]),
    				'pricecategory' => trim($data[3]),
    				'price' => trim($data[4]));
    	
    	}
    	
    	$rows = $dom_new->getElementsByTagName('Row');
    	
    	$first_row = TRUE;
    	
    	foreach($rows as $row)
    	{
    		$cells = $row->getElementsByTagName('Cell');
    		 
    		if($cells->length == '0')
    			continue;
    		 
    		$data = array();
    		 
    		foreach($cells as $cell)
    		{
    			if(!$first_row)
    			{
    				$data[] = $cell->nodeValue;
    			}
    			else
    			{
    				$first_row = FALSE;
    				break;
    			}
    		}
    		
    		if(!isset($data[0]))
    		{
    			continue;
    		}
    		
    		$new_courses[trim($data[0])] = array('title' => trim($data[0]));
    	}
    	
    	$target_courses = array_intersect_key($old_courses, $new_courses);
    	$target_courses = array_merge($target_courses, array_diff_key($new_courses, $old_courses));
    	
    	
    	$out_data = '';
    	foreach($target_courses as $new_course)
    	{
    		if(isset($new_course['title']))
    			$out_data .= $new_course['title'];
    	
    		$out_data .= '|';
    	
    		if(isset($new_course['cluster']))
    			$out_data .= $new_course['cluster'];
    	
    		$out_data .= '|';
    	
    		if(isset($new_course['code']))
    			$out_data .= $new_course['code'];
    	
    		$out_data .= '|';
    	
    		if(isset($new_course['pricecategory']))
    			$out_data .= $new_course['pricecategory'];
    	
    		$out_data .= '|';
    	
    		if(isset($new_course['price']))
    			$out_data .= $new_course['price'];
    	
    		$out_data .= '|';
    	
    	
    	
    	
    	
    		$out_data .= "\n";
    	}
    	
    	header("Content-Type: text/csv");
    	header( "Content-Description: csv File" );
    	header( "Content-Disposition: attachment; filename=blubb.csv");
		  header( "Pragma: no-cache" ); 
		  header( "Expires: 0" ); 
		 echo $out_data;
		 
		 $this->set_layout_view(FALSE);
    	exit();

    	   
    }
}

/* End of file katalog.php */
/* Location: ./application/controllers/katalog.php */